package com.controller;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.model.auto.MendaoStu;
import com.model.auto.MendaoTest;
import com.model.auto.MendaoTestReport;
import com.model.auto.MendaoTopicLibrary;
import com.model.auto.req.*;
import com.model.auto.resp.*;
import com.service.IMendaoStuService;
import com.service.IMendaoTestReportService;
import com.service.IMendaoTestService;
import com.service.IMendaoTopicLibraryService;
import com.util.R;
import com.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author astupidcoder
 * @since 2022-09-14
 */
@RestController
@RequestMapping("/mendao")
public class MendaoTestController{
    @Autowired
    private IMendaoTopicLibraryService topicLibraryService;
    @Autowired
    private IMendaoTestService mendaoTestService;
    @Autowired
    private IMendaoTestReportService testReportService;
    @Autowired
    private IMendaoStuService mendaoStuService;


    //查询学生测评记录
    @GetMapping("/getMenDaoStu")
    public R getMenDaoStu(String stuId) {
        if (StringUtil.isEmpty(stuId)) {
            return R.error("参数为空");
        }
        String bindStuId = "zj" + stuId;
        List<MendaoStu> stuList = mendaoStuService.list(new LambdaQueryWrapper<MendaoStu>()
                .eq(MendaoStu::getBindStuId, bindStuId)
                .orderByDesc(MendaoStu::getId)
        );
        if(!ObjectUtils.isEmpty(stuList) && stuList.size()>0){
            return R.ok(stuList.get(0));
        }else{
            return R.ok("未查询到记录");
        }
    }

    @PostMapping("/bindTest")
    public R bindTest(@RequestBody BindTestReq req) {
        String phone = req.getPhone();
        List<MendaoStu> stuList = mendaoStuService.list(new LambdaQueryWrapper<MendaoStu>()
                .eq(MendaoStu::getPhone, phone)
                .eq(MendaoStu::getStuName, req.getStuName())
                .orderByDesc(MendaoStu::getId)
        );
        if (!ObjectUtils.isEmpty(stuList) && stuList.size() > 0) {
            MendaoStu mendaoStu = stuList.get(0);
            if (Objects.isNull(mendaoStu.getBindStuId()) || mendaoStu.getBindStuId().equals("zj" + req.getStuId())) {
                mendaoStu.setBindStuId("zj" + req.getStuId());
                mendaoStuService.updateById(mendaoStu);
                return R.ok("绑定成功");
            } else {
                return R.error("该手机号码测评记录已经被绑定");
            }
        } else {
            return R.error("未查询到该手机号码测评记录");
        }
    }
    @ResponseBody
    @RequestMapping(value = "/addTest")
    public R addTest(HttpServletRequest request){
        try{
            String data = request.getParameter("data");
            System.out.println("addTest---->"+data);
            if(data == null){
                return R.error("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);
            if(mendaoTestReq != null && mendaoTestReq.getTestId()>0){
                MendaoTest oldMendaoTest = mendaoTestService.findOne(mendaoTestReq.getTestId());
                oldMendaoTest.setName(mendaoTestReq.getTestName());
                oldMendaoTest.setImage(mendaoTestReq.getTestImage());
                oldMendaoTest.setIntroduction(mendaoTestReq.getTestIntroduction());
                oldMendaoTest.setTestDesc(mendaoTestReq.getTestDesc());
                oldMendaoTest.setTopicGroup(mendaoTestReq.getTopicGroup());

                if(mendaoTestReq.getTopicGroup() != null && !mendaoTestReq.getTopicGroup().equals("")){
                    List<MendaoTopicGroupResp> topicGroupList = JSONObject.parseArray(mendaoTestReq.getTopicGroup(),MendaoTopicGroupResp.class);
                    List<MendaoTopicGroupResp> saveList = new ArrayList<>();
                    int i = 1;
                    for(MendaoTopicGroupResp topicGroup:topicGroupList){
                        topicGroup.setTopicGroupId(mendaoTestReq.getTestId()+"_"+String.format("%04d", i));
                        saveList.add(topicGroup);
                        i++;
                    }
                    oldMendaoTest.setTopicGroup(JSONObject.toJSONString(saveList));
                }

                mendaoTestService.updateDate(oldMendaoTest);
                return R.ok("请求成功",mendaoTestReq.getTestId());
            }else{
                if(mendaoTestReq == null){
                    return R.error("参数错误");
                }

                MendaoTest mendaoTest = new MendaoTest();
                mendaoTest.setImage(mendaoTestReq.getTestImage());
                mendaoTest.setName(mendaoTestReq.getTestName());
                mendaoTest.setTestDesc(mendaoTestReq.getTestDesc());
                mendaoTest.setIntroduction(mendaoTestReq.getTestIntroduction());
                mendaoTest.setStatus(1);

                mendaoTestService.insertDate(mendaoTest);
                System.out.println(mendaoTest.getId());
                if(mendaoTestReq.getTopicGroup() != null && !mendaoTestReq.getTopicGroup().equals("")){
                    List<MendaoTopicGroupResp> topicGroupList = JSONObject.parseArray(mendaoTestReq.getTopicGroup(),MendaoTopicGroupResp.class);
                    List<MendaoTopicGroupResp> saveList = new ArrayList<>();
                    int i = 1;
                    for(MendaoTopicGroupResp topicGroup:topicGroupList){
                        topicGroup.setTopicGroupId(mendaoTest.getId()+"_"+String.format("%04d", i));
                        saveList.add(topicGroup);
                        i++;
                    }
                    mendaoTest.setTopicGroup(JSONObject.toJSONString(saveList));
                    mendaoTestService.updateDate(mendaoTest);
                }
                return R.ok("请求成功",mendaoTest.getId());
            }
        }catch (Exception e){
            e.printStackTrace();
            return R.error("发生异常");
        }
    }


    @ResponseBody
    @RequestMapping(value = "/getTest")
    public Object getTest(HttpServletRequest request) {
        BaseRespList resp = new BaseRespList();
        try{

            String data = request.getParameter("data");
            System.out.println("getTest---->"+data);
            if(data == null){
                resp.setCode(0);
                resp.setMsg("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);
            List<MendaoTestResp> respList = new ArrayList<MendaoTestResp>();
            //type=1后台获取全部type=2前台获取列表
            List<MendaoTest> list = mendaoTestService.getList(mendaoTestReq.getType());
            if(list != null && list.size()>0){
                for(MendaoTest test:list){
                    MendaoTestResp mendaoTestResp = new MendaoTestResp();
                    mendaoTestResp.setTestId(test.getId());
                    mendaoTestResp.setTestName(test.getName());
                    mendaoTestResp.setTestImage(test.getImage());
                    mendaoTestResp.setTestIntroduction(test.getIntroduction());
                    mendaoTestResp.setTestDesc(test.getTestDesc());
                    mendaoTestResp.setStatus(test.getStatus());
                    respList.add(mendaoTestResp);
                }
            }

            resp.setList(respList);
            resp.setCode(1);
            resp.setMsg("请求成功");
        }catch (Exception e){
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }
        return resp;

    }


    @RequestMapping(value = "/getTestById")
    public Object getTestById(HttpServletRequest request) {
        BaseRespData resp = new BaseRespData();
        try {

            String data = request.getParameter("data");
            System.out.println("getTestById---->" + data);
            if (data == null) {
                resp.setCode(0);
                resp.setMsg("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);
            MendaoTest mendaoTest = mendaoTestService.findOne(mendaoTestReq.getTestId());

            MendaoTestResp testResp = new MendaoTestResp();
            testResp.setTestId(mendaoTest.getId());
            testResp.setTestName(mendaoTest.getName());
            testResp.setTestImage(mendaoTest.getImage());
            testResp.setTestDesc(mendaoTest.getTestDesc());
            testResp.setTestIntroduction(mendaoTest.getIntroduction());
            testResp.setStatus(mendaoTest.getStatus());

            resp.setData(testResp);
            resp.setCode(1);
            resp.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }

        return resp;
    }


    @ResponseBody
    @RequestMapping(value = "/getTopicByTestId")
    public Object getTopicByTestId(HttpServletRequest request) {
        BaseRespList resp = new BaseRespList();
        try {
            String data = request.getParameter("data");
            System.out.println("getTopicByTestId---->" + data);
            if (data == null) {
                resp.setCode(0);
                resp.setMsg("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);

            List<MendaoTopicGroupResp> respList = new ArrayList<MendaoTopicGroupResp>();
            MendaoTest mendaoTest = mendaoTestService.findOne(mendaoTestReq.getTestId());
            if (mendaoTest.getTopicGroup() != null && !"".equals(mendaoTest.getTopicGroup())) {
                respList = JSONArray.parseArray(mendaoTest.getTopicGroup(), MendaoTopicGroupResp.class);
            }

            resp.setList(respList);
            resp.setCode(1);
            resp.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }
        return resp;

    }

    @RequestMapping(value = "/getTopicLibrary")
    public Object getTopicLibrary(HttpServletRequest request) {

        BaseRespList resp = new BaseRespList();
        try {
            String data = request.getParameter("data");
            System.out.println("getTopicLibrary---->" + data);
            if (data == null) {
                resp.setCode(0);
                resp.setMsg("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);

            List<MendaoTopicLibraryResp> respList = new ArrayList<MendaoTopicLibraryResp>();

            List<MendaoTopicLibrary> list = topicLibraryService.getListByTestId(mendaoTestReq.getTestId());
            if (list != null && list.size() > 0) {
                for (MendaoTopicLibrary test : list) {
                    MendaoTopicLibraryResp topicLibraryResp = new MendaoTopicLibraryResp();
                    topicLibraryResp.setTopicLibraryName(test.getTopicLibraryName());
                    topicLibraryResp.setTopicGroupId(test.getTopicGroupId());
                    topicLibraryResp.setOptions(test.getOptions());
                    respList.add(topicLibraryResp);
                }
            }
            resp.setList(respList);
            resp.setCode(1);
            resp.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }
        return resp;
    }

    @PostMapping(value = "/commitTest")
    public Object commitTest(@RequestBody MendaoTestReq mendaoTestReq) {
        MendaoCommitStuResp resp = new MendaoCommitStuResp();
        try {
            System.out.println("commitTest---->" + mendaoTestReq);

            MendaoStu mendaoStu = new MendaoStu();
            if (mendaoTestReq.getId() != null) {
                mendaoStu.setId(mendaoTestReq.getId());
            }
            mendaoStu.setTestId(mendaoTestReq.getTestId());
            mendaoStu.setStuName(mendaoTestReq.getStuName());
            mendaoStu.setSchoolName(mendaoTestReq.getSchoolName());
            mendaoStu.setPhone("zj" + mendaoTestReq.getStuId());
            mendaoStu.setBindStuId("zj" + mendaoTestReq.getStuId());
            mendaoStu.setList(JSON.toJSONString(mendaoTestReq.getList()));
            mendaoStu.setCreatedTime(new Date());
            mendaoStuService.saveOrUpdate(mendaoStu);
            resp.setTestId(mendaoTestReq.getTestId());
            resp.setStuId(mendaoStu.getId());
            resp.setCode(1L);
            resp.setMsg("请求成功");
        } catch (Exception var6) {
            var6.printStackTrace();
            resp.setCode(0L);
            resp.setMsg("发生异常");
        }
        return resp;
    }

    @PostMapping("/showCommitTest")
    public Object showCommitTest(@RequestBody MendaoTestReq mendaoTestReq) {

        BaseRespData resp = new BaseRespData();
        try {
            System.out.println("showCommitTest---->" + mendaoTestReq);

            System.out.println("==========stuid=====" + mendaoTestReq.getStuId());
            MendaoStu mendaoStu = this.mendaoStuService.findOne(mendaoTestReq.getStuId());
            List<TestTimu> testTimuList = JSONArray.parseArray(mendaoStu.getList(), TestTimu.class);
            mendaoTestReq.setList(testTimuList);
            if (mendaoTestReq.getList() != null && mendaoTestReq.getList().size() > 0) {
                List<TestTimu> list = mendaoTestReq.getList();
                Map<String, Integer> map = new HashMap<>();
                for (TestTimu timu : list) {
                    if (map.containsKey(timu.getTopicGroupId())) {
                        map.put(timu.getTopicGroupId(), map.get(timu.getTopicGroupId()) + timu.getScore());
                    } else {
                        map.put(timu.getTopicGroupId(), timu.getScore());
                    }
                }


                MendaoCommitResp commitResp = new MendaoCommitResp();

                List<MendaoTestReport> reportList = testReportService.getListByTestId(mendaoTestReq.getTestId());
                MendaoTest mendaoTest = mendaoTestService.findOne(mendaoTestReq.getTestId());

                if (reportList != null && reportList.size() > 0) {
                    MendaoTestReport report = reportList.get(0);

                    commitResp.setTestName(mendaoTest.getName());
                    if (report.getIsShowReportDesc() == 1) {
                        commitResp.setReportDesc(report.getReportDesc());
                    }
                    //得分list
                    List<TableTestMsg> tableTestMsgList = new ArrayList<>();
                    //图标设置
                    if (report.getIsShowTableSet() == 1) {
                        MendaoTableSet mendaoTableSet = JSONObject.parseObject(report.getTableSet(), MendaoTableSet.class);
                        commitResp.setTableTitle(mendaoTableSet.getTableTitle());

                        MendaoTablesSetResp mendaoTablesSetResp = new MendaoTablesSetResp();
                        mendaoTablesSetResp.setTableName(mendaoTableSet.getTableName());
                        mendaoTablesSetResp.setTableColor(mendaoTableSet.getTableColor());

                        List<TopicGroup> topicGroupList = JSONArray.parseArray(mendaoTest.getTopicGroup(), TopicGroup.class);
                        for (TopicGroup topicGroup : topicGroupList) {
                            TableTestMsg tableTestMsg = new TableTestMsg();
                            tableTestMsg.setTopicGroupId(topicGroup.getTopicGroupId());
                            tableTestMsg.setTopicGroupCode(topicGroup.getTopicGroupCode());
                            tableTestMsg.setUnitName(topicGroup.getTopicGroupName());
                            tableTestMsg.setUnitScore(map.get(topicGroup.getTopicGroupId()) + "");

                            tableTestMsgList.add(tableTestMsg);
                        }
                        tableTestMsgList.sort(Comparator.comparingInt(x -> Integer.parseInt(x.getUnitScore())));
                        Collections.reverse(tableTestMsgList);
                        mendaoTablesSetResp.setTableTestMsg(tableTestMsgList);

                        commitResp.setTableSet(mendaoTablesSetResp);
                    }

                    HashMap<String, Object> listmap = new HashMap<String, Object>();
                    tableTestMsgList.forEach(i -> {
                        if (i.getTopicGroupCode().equals("R")) {
                            listmap.put("R", i);
                        } else if (i.getTopicGroupCode().equals("I")) {
                            listmap.put("I", i);
                        } else if (i.getTopicGroupCode().equals("A")) {
                            listmap.put("A", i);
                        } else if (i.getTopicGroupCode().equals("S")) {
                            listmap.put("S", i);
                        } else if (i.getTopicGroupCode().equals("E")) {
                            listmap.put("E", i);
                        } else if (i.getTopicGroupCode().equals("C")) {
                            listmap.put("C", i);
                        }
                    });

                    //图标总结

                    if (report.getIsShowTableResult() == 1) {
                        MendaoTableResult tableResult = JSONObject.parseObject(report.getTableResult(), MendaoTableResult.class);

                        MendaoTableResultResp tableResultResp = new MendaoTableResultResp();
                        tableResultResp.setUpContent(tableResult.getUpDesc());
                        StringBuffer downContent = new StringBuffer();
                        for (int i = 0; i < tableResult.getTopNum(); i++) {
                            if (i == 0) {
                                downContent.append(tableTestMsgList.get(i).getUnitName());
                            } else {
                                downContent.append(tableResult.getSplitDesc());
                                downContent.append(tableTestMsgList.get(i).getUnitName());
                            }
                        }
                        tableResultResp.setDownContent(downContent.toString());

                        commitResp.setTableResult(tableResultResp);
                    }
                    //题组总结
                    if (report.getIsShowTopicReportList() == 1) {
                        MendaoTopicReport topicReport = JSONObject.parseObject(report.getTopicReport(), MendaoTopicReport.class);

                        MendaoTopicReportResp topicReportResp = new MendaoTopicReportResp();

                        topicReportResp.setTopicReportTitle(topicReport.getTitleWarning());

                        if (topicReport.getTopicReportList() != null && topicReport.getTopicReportList().size() > 0) {
                            List<TopicReport> topicReportBeanList = new ArrayList<>();
                            if (topicReport.getOrderType() == 1) {
                                List<TopicGroup> topicGroupList = JSONArray.parseArray(mendaoTest.getTopicGroup(), TopicGroup.class);
                                for (int i = 0; i < topicReport.getShowNum(); i++) {
                                    TopicReport topicReportBean = new TopicReport();

                                    int score = map.get(topicGroupList.get(i).getTopicGroupId());
                                    for (MendaoTopicReportList topicReportList : topicReport.getTopicReportList()) {
                                        if (topicReportList.getTopicGroupId().equals(topicGroupList.get(i).getTopicGroupId())) {
                                            topicReportBean.setTitle(topicReportList.getTitle());
                                            for (MendaoSocreReport socreReport : topicReportList.getSocreReport()) {
                                                if (score >= socreReport.getTopSocre() && score <= socreReport.getDownSocre()) {
                                                    topicReportBean.setContent(socreReport.getSocreDesc());
                                                    break;
                                                }
                                            }
                                            topicReportBeanList.add(topicReportBean);
                                            break;
                                        }
                                    }
                                }
                            } else {
                                for (int i = 0; i < topicReport.getShowNum(); i++) {

                                    TopicReport topicReportBean = new TopicReport();
                                    int score = map.get(tableTestMsgList.get(i).getTopicGroupId());
                                    for (MendaoTopicReportList topicReportList : topicReport.getTopicReportList()) {
                                        if (topicReportList.getTopicGroupId().equals(tableTestMsgList.get(i).getTopicGroupId())) {
                                            topicReportBean.setTitle(topicReportList.getTitle());
                                            for (MendaoSocreReport socreReport : topicReportList.getSocreReport()) {
                                                if (score > socreReport.getTopSocre() && score < socreReport.getDownSocre()) {
                                                    topicReportBean.setContent(socreReport.getSocreDesc());
                                                    break;
                                                }
                                            }
                                            topicReportBeanList.add(topicReportBean);
                                            break;
                                        }
                                    }
                                }
                            }

                            topicReportResp.setTopicReportList(topicReportBeanList);
                        }
                        commitResp.setTopicReport(topicReportResp);
                    }
                    //更多建议
                    if (report.getIsShowMoreSuggest() == 1) {
                        commitResp.setMoreSuggestTitle(report.getMoreSuggestTitle());

                        List<TopicReport> moreSuggestRespList = new ArrayList<>();

                        List<MendaoMoreSuggest> moreSuggestList = JSONArray.parseArray(report.getMoreSuggest(), MendaoMoreSuggest.class);

                        for (MendaoMoreSuggest moreSuggest : moreSuggestList) {
                            int length = moreSuggest.getSuggestCode().length();
                            StringBuffer codeString = new StringBuffer();
                            for (int i = 0; i < length; i++) {
                                codeString.append(tableTestMsgList.get(i).getTopicGroupCode());
                            }
                            if (moreSuggest.getSuggestCode().equals(codeString.toString())) {
                                TopicReport moreSuggestResp = new TopicReport();
                                for (MendaoSuggestArray array : moreSuggest.getSuggestArray()) {
                                    moreSuggestResp.setTitle(array.getSuggestTitle());
                                    moreSuggestResp.setContent(array.getSuggestContent());
                                    moreSuggestRespList.add(moreSuggestResp);
                                }
                            }
                        }

                        commitResp.setMoreSuggest(moreSuggestRespList);
                    }
                    tableTestMsgList.set(0, (TableTestMsg) listmap.get("I"));
                    tableTestMsgList.set(1, (TableTestMsg) listmap.get("R"));
                    tableTestMsgList.set(2, (TableTestMsg) listmap.get("C"));
                    tableTestMsgList.set(3, (TableTestMsg) listmap.get("E"));
                    tableTestMsgList.set(4, (TableTestMsg) listmap.get("S"));
                    tableTestMsgList.set(5, (TableTestMsg) listmap.get("A"));
                    //测评总结
                    if (report.getIsShowReportResult() == 1) {
                        commitResp.setReportResult(report.getReportResult());
                    }

                    //测试尾图
                    if (report.getIsShowLastImage() == 1) {
                        commitResp.setLastImage(report.getLastImage());
                    }

                    resp.setData(commitResp);
                }
            } else {
                resp.setCode(0);
                resp.setMsg("参数为空");
            }
            resp.setCode(1);
            resp.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }
        return resp;

    }

    @ResponseBody
    @RequestMapping(value = "/getTestReport")
    public Object getTestReport(HttpServletRequest request) {
        BaseRespData resp = new BaseRespData();
        try {
            String data = request.getParameter("data");
            System.out.println("getTestReport---->" + data);
            if (data == null) {
                resp.setCode(0);
                resp.setMsg("参数为空");
            }

            MendaoTestReq mendaoTestReq = JSONObject.parseObject(data, MendaoTestReq.class);

            List<MendaoTopicLibraryResp> respList = new ArrayList<MendaoTopicLibraryResp>();

            List<MendaoTestReport> list = testReportService.getListByTestId(mendaoTestReq.getTestId());
            if (list != null && list.size() > 0) {
                MendaoTestReport report = list.get(0);
                resp.setData(report);
            }

            resp.setCode(1);
            resp.setMsg("请求成功");
        } catch (Exception e) {
            e.printStackTrace();
            resp.setCode(0);
            resp.setMsg("发生异常");
        }
        return resp;
    }

}
